package com.csc.contact.checkbill.utiltools.sftputil;

import com.csc.contact.checkbill.entity.ReconciliationInfo;
import com.csc.contact.checkbill.service.ReconciliationServiceImpl;
import com.csc.contact.checkbill.controller.ReadFileFromFTPTask;
import com.csc.contact.checkbill.utiltools.ftp.FtpConfig;
import com.csc.contact.checkbill.utiltools.ftputils.FtpReadFile;
import com.csc.contact.checkbill.utiltools.ftputils.FtpReadFileImpl;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.*;

public class SftpUtil {

    private Session sshSession = null;
    private Channel channel = null;
    private ChannelSftp sftp = null;
    private static Logger logger = Logger.getLogger(SftpUtil.class);

    public ChannelSftp getConnect(String host, int port, String userName, String passWord) {
        try {
            JSch jsch = new JSch();
            jsch.getSession(userName, host, port);
            sshSession = jsch.getSession(userName, host, port);
            logger.info("Session created.");
            sshSession.setPassword(passWord);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            logger.info("Session connected.");
            channel = sshSession.openChannel("sftp");
            channel.connect();
            logger.info("Opening Channel.");
            sftp = (ChannelSftp) channel;
            logger.info("Connected to " + host + ".");
        } catch (Exception e) {
            logger.info("连接sftp服务器异常====", e);
        }
        logger.info("连接sftp服务器成功====");

        return sftp;
    }

    /**
     * 打开或进入目录
     *
     * @param directory
     * @param sftp
     * @return
     */
    public boolean openDir(String directory, ChannelSftp sftp) {
        try {
            logger.info("进入文件目录" + directory);
            sftp.cd(directory);
            return true;
        } catch (SftpException e) {
            logger.error("进入文件目录====", e);
            return false;
        }
    }

    /**
     * 打开或进入目录
     *
     * @param oldPath
     * @param newPath
     * @return
     */
    public boolean rename(String oldPath, String newPath, String type) {
        try {
            getSftp(type);
            sftp.rename(oldPath, newPath);
            return true;
        } catch (SftpException e) {
            logger.error("移动文件异常信息=======", e);
            return false;
        }
    }

    private void getSftp(String type) {
        if (!isConnect()) {
            if ("sn".equals(type)) {
                logger.info("获取写回执文件的sftp");
                getConnect(FtpConfig.config.get("ftp.ip"), Integer.parseInt(FtpConfig.config.get("ftp.port")), FtpConfig.config.get("ftp"
                        + ".userName"), FtpConfig.config.get("ftp.passwd"));
            } else {
                logger.info("获取写给号卡文件的sftp");
                getConnect(FtpConfig.config.get("hk.ip"), Integer.parseInt(FtpConfig.config.get("hk.port")), FtpConfig.config.get("hk" +
                        ".userName"), FtpConfig.config.get("hk.passwd"));
            }
        }
    }

    /**
     * 上传文件
     *
     * @param directory  上传的目录
     * @param uploadFile 要上传的文件
     */
    public boolean upload(String directory, String uploadFile, String type) {
        InputStream input = null;
        try {
            logger.info("上传文件路径====" + directory);
            getSftp(type);
            sftp.cd(directory);
            File file = new File(uploadFile);
            input = new FileInputStream(file);
            sftp.put(input, file.getName());
            logger.info("上传完成");
            input.close();
            return true;
        } catch (Exception e) {
            logger.info("文件上传失败===", e);
            return false;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException io) {
                    logger.info("关闭文件流失败====", io);
                }

            }
        }
    }

    /**
     * 下载文件
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     */
    public void download(String directory, String downloadFile, String saveFile) {
        try {
            if (!isConnect()) {
                getConnect(FtpConfig.config.get("ftp.ip"), Integer.parseInt(FtpConfig.config.get("ftp.port")), FtpConfig.config.get("ftp"
                        + ".userName"), FtpConfig.config.get("ftp.passwd"));
            }
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
            logger.info("下载完成");
        } catch (Exception e) {
            logger.info("文件下载失败===", e);
        }
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public void delete(String directory, String deleteFile) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            logger.info("文件删除失败====", e);
        }

    }

    /**
     * 列出目录下的文件
     *
     * @param directory 要列出的目录
     * @return
     * @throws SftpException
     */
    @SuppressWarnings("rawtypes")
    public Vector listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    /**
     * 关闭链接
     */
    public void close() {
        if (sftp != null) {
            sftp.quit();
        }
        if (channel != null) {
            channel.disconnect();
        }
        if (sshSession != null) {
            sshSession.disconnect();
        }
    }

/*    *//**
     * 上传流
     *
     * @param sInputString 要上传的字符串
     * @param directory    上传的目录
     * @param dst          目标文件名
     *//*
    public void upload(String sInputString, String directory, String dst) {
        try {
            sftp.cd(directory);
            InputStream is = getStringStream(new String(sInputString.getBytes(), "GBK"));
            sftp.put(is, dst);
            logger.info("上传完成");
        } catch (Exception e) {
            logger.info("文件上传流失败====", e);
        }
    }*/

    /**
     * 下载流
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     */
    public String download(String directory, String downloadFile) {
        try {
            sftp.cd(directory);
            InputStream is = sftp.get(downloadFile);
            logger.info("下载完成");
            return changeStreamToString(is);
        } catch (Exception e) {
            logger.info("文件下载流失败====", e);
            return null;
        }
    }

    /**
     * 将字符串转化为InputStream流
     */
    public static InputStream getStringStream(String sInputString) {
        ByteArrayInputStream tInputStringStream = null;
        try {
            tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
            return tInputStringStream;
        } catch (Exception ex) {
            logger.info("getStringStream 异常信息====", ex);
        } finally {
            if (tInputStringStream != null) {
                try {
                    tInputStringStream.close();
                } catch (NullPointerException e) {
                    logger.info("getStringStream Finally 空指针异常信息====", e);
                } catch (IOException e) {
                    logger.info("getStringStream Finally IO异常信息====", e);
                }
            }

        }
        return null;
    }

    /**
     * 将InputStream流转为String
     */
    public static String changeStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            logger.info("changeStreamToString异常信息====", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                logger.info("changeStreamToString Finally异常信息====", e);
            }
        }
        return sb.toString();
    }


    public String formatDirPath(String cDst) {
        String tStr = cDst;
        if ("/".equals(tStr) || "\\".equals(tStr)) {
            return tStr;
        }
        if (cDst.endsWith("/")) {
            tStr = tStr.substring(0, cDst.length() - 1);
        }
        if (cDst.endsWith("\\")) {
            tStr = tStr.substring(0, cDst.length() - 2);
        }
        return tStr;
    }


    public boolean isConnect() {
        return (this.sftp != null && this.sftp.isConnected() && this.sshSession != null && this.sshSession.isConnected());
    }


    /**
     * 读取文件
     *
     * @param fileName
     * @param strencoding
     * @param filePath
     * @param ftpReadFile
     * @param reconciliationInfos
     * @param reconciliationService
     * @return
     */
    public boolean readFile(String fileName, String strencoding, String filePath, FtpReadFile ftpReadFile, List<ReconciliationInfo>
            reconciliationInfos, ReconciliationServiceImpl reconciliationService,List<String> queryY,String proY) {
        InputStream in = null;
        InputStream input = null;
        try {
            if (!isConnect()) {
                getConnect(FtpConfig.config.get("ftp.ip"), Integer.parseInt(FtpConfig.config.get("ftp.port")), FtpConfig.config.get("ftp"
                        + ".userName"), FtpConfig.config.get("ftp.passwd"));
            }
            input = sftp.get(fileName);
            in = sftp.get(fileName);
            if (in == null) throw new FileNotFoundException();
            if (input == null) throw new FileNotFoundException();
            String s = IOUtils.toString(input);
            String[] rechargeArr = s.split("\n");
            List<String> list  = Arrays.asList(rechargeArr);
            String lastLineStr = list.get(list.size() - 1);
            logger.info("--------最后一行数据--------:"+lastLineStr);
            input.close();
            //判断文件是否已经上传完毕
            if (lastLineStr.contains("TOTAL_COUNT") && lastLineStr.contains("TOTAL_MONEY")) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, strencoding));
                String line;
                Integer i = 1;
                try {
                    while ((line = reader.readLine()) != null) {
                        logger.info("读取的文件内容====" + line);
                        ftpReadFile.readFile(fileName, line, i, reconciliationInfos, reconciliationService, queryY, proY);
                        if(line.contains("TOTAL_COUNT") && line.contains("TOTAL_MONEY")){
                            logger.info("当前为最后一行，文件入库成功");
                        }else{
                            i++;
                        }
                    }
                    logger.info("文件中数据行数====" + i);
                    logger.info("reconciliationInfos size=====" + reconciliationInfos.size());
                    logger.info("list对象中的实体类值 " + reconciliationInfos.get(0).toString());
                    //如果提交数据小于1000，再这里进行提交
                    if (i % ReadFileFromFTPTask.BATCHSIZE != 0 && FtpReadFileImpl.dataNum != 0) {
                        reconciliationService.batchReconciliationInfo(reconciliationInfos);
                        FtpReadFileImpl.dataNum = 0;
                        logger.info(fileName + "第" + (i / ReadFileFromFTPTask.BATCHSIZE + 1) + "批数据导入完成," + i);
                        reconciliationInfos.clear();
                    }
                    reader.close();
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("文件读取错误。", e);
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            logger.debug("本地文件下载失败！", e);
        } finally {
            try {
                if (in != null) in.close();
                if (input != null) input.close();
            } catch (Exception e) {
                logger.info("错误信息===", e);
            }
        }
        logger.info("文件读取结束=====");
        return true;
    }

    public List<String> getFiles(ChannelSftp cChannelSftp, String cDir) throws SftpException {
        List<String> tFiles = new ArrayList<String>();


        cDir = formatDirPath(cDir);


        Vector<ChannelSftp.LsEntry> tfs = null;
        if ("".equals(cDir) || cDir == null) {
            logger.info("cDir:地址为空！");
            return null;
        }
        if (!cChannelSftp.isConnected()) {
            logger.info("ChannelSftp:未建立连接！");
            return null;
        }
        tfs = cChannelSftp.ls(cDir);


        for (ChannelSftp.LsEntry tEntry : tfs) {
            SftpATTRS attrs = tEntry.getAttrs();
            if (!attrs.isDir()) {
                logger.info("文件名称====" + tEntry.getFilename() + "=======文件大小====" + attrs.getSize());
                if (attrs.getSize() > 10) {
                    tFiles.add(tEntry.getFilename());
                }
            }
        }
        return tFiles;
    }
}